package com.ship.dispatch.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ship.common.business.service.impl.BaseServiceImpl;
import com.ship.common.core.base.Page;
import com.ship.common.core.domain.R;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.dispatch.bean.TzFuelDelivery;
import com.ship.dispatch.bean.TzFuelReport;
import com.ship.dispatch.bean.fob.SpFobFileRecord;
import com.ship.dispatch.bo.TzFuelDeliveryLsmgoBo;
import com.ship.dispatch.bo.TzFuelDeliveryVlsfoBo;
import com.ship.dispatch.service.TzFuelDeliveryService;
import com.ship.dispatch.mapper.TzFuelDeliveryMapper;
import com.ship.dispatch.service.TzFuelReportService;
import com.ship.dispatch.service.fob.SpFobFileRecordService;
import com.ship.system.api.RemoteFileService;
import com.ship.system.api.domain.SysFile;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
* @author zhangyh
* @description 针对表【tz_fuel_delivery(燃油台账交还船信息)】的数据库操作Service实现
* @createDate 2024-06-17 11:27:11
*/
@Service
public class TzFuelDeliveryServiceImpl extends BaseServiceImpl<TzFuelDeliveryMapper, TzFuelDelivery>
    implements TzFuelDeliveryService{

    @Autowired
    @Lazy
    private TzFuelReportService tzFuelReportService;

    @Resource
    private SpFobFileRecordService spFobFileRecordService;

    @Resource
    private RemoteFileService remoteFileService;

    @Override
    public void fuelUpdateDeliveryInfo(Date fuelTime, String shipName){
        List<TzFuelDelivery> deliveryList = this.baseMapper.selectList(
                new LambdaQueryWrapper<TzFuelDelivery>()
                .ge(TzFuelDelivery::getDeliveryTime,fuelTime)
                .eq(TzFuelDelivery::getShipName,shipName)
        );
        for (TzFuelDelivery fuelDelivery : deliveryList) {
            //数据处理逻辑
            fuelDelivery = resetDeliveryData(fuelDelivery);
            this.baseMapper.updateById(fuelDelivery);
        }
    }

    /**
     * 加油数据同步
     * @param dto
     * @return
     */
    public TzFuelDelivery resetDeliveryData(TzFuelDelivery dto){
        BigDecimal vlsfoSettlement = BigDecimal.ZERO;
        BigDecimal lsmgoSettlement = BigDecimal.ZERO;
        BigDecimal lsmgo = BigDecimal.ZERO;
        BigDecimal lsmgoPrice = BigDecimal.ZERO;
        BigDecimal vlsfo = BigDecimal.ZERO;
        BigDecimal vlsfoPrice = BigDecimal.ZERO;
        if(dto.getVlsfoThree() != null && dto.getVlsfoThreePrice() != null){
            vlsfo = vlsfo.add(dto.getVlsfoThree());
            vlsfoPrice = dto.getVlsfoThreePrice();
            vlsfoSettlement = vlsfoSettlement.add(dto.getVlsfoThree().multiply(dto.getVlsfoThreePrice()));
        }
        if(dto.getVlsfoTwoPrice() != null && dto.getVlsfoTwo() != null){
            vlsfo = vlsfo.add(dto.getVlsfoTwo());
            vlsfoPrice = dto.getVlsfoTwoPrice();
            vlsfoSettlement = vlsfoSettlement.add(dto.getVlsfoTwo().multiply(dto.getVlsfoTwoPrice()));
        }
        if(dto.getVlsfoOne() != null && dto.getVlsfoOnePrice() != null){
            vlsfo = vlsfo.add(dto.getVlsfoOne());
            vlsfoPrice = dto.getVlsfoOnePrice();
            vlsfoSettlement = vlsfoSettlement.add(dto.getVlsfoOne().multiply(dto.getVlsfoOnePrice()));
        }

        if(dto.getLsmgoThree() != null && dto.getLsmgoThreePrice() != null){
            lsmgo = lsmgo.add(dto.getLsmgoThree());
            lsmgoPrice = dto.getLsmgoThreePrice();
            lsmgoSettlement = lsmgoSettlement.add(dto.getLsmgoThree().multiply(dto.getLsmgoThreePrice()));
        }
        if(dto.getLsmgoTwo() != null && dto.getLsmgoTwoPrice() != null){
            lsmgo = lsmgo.add(dto.getLsmgoTwo());
            lsmgoPrice = dto.getLsmgoTwoPrice();
            lsmgoSettlement = lsmgoSettlement.add(dto.getLsmgoTwo().multiply(dto.getLsmgoTwoPrice()));
        }
        if(dto.getLsmgoOne() != null && dto.getLsmgoOnePrice() != null){
            lsmgo = lsmgo.add(dto.getLsmgoOne());
            lsmgoPrice = dto.getLsmgoOnePrice();
            lsmgoSettlement = lsmgoSettlement.add(dto.getLsmgoOne().multiply(dto.getLsmgoOnePrice()));
        }


        dto.setVlsfoSettlement(vlsfoSettlement.setScale(4, RoundingMode.HALF_UP));
        dto.setLsmgoSettlement(lsmgoSettlement.setScale(4, RoundingMode.HALF_UP));
        dto.setVlsfo(vlsfo);
        dto.setVlsfoPrice(vlsfoPrice);
        dto.setLsmgo(lsmgo);
        dto.setLsmgoPrice(lsmgoPrice);



        //台账计算逻辑
//        if(dto.getVlsfo() != null){
//            //获取交还船时间之前的三条记录
//            List<TzFuelReport> fuelReports = tzFuelReportService.getBaseMapper().selectList(
//                    new LambdaQueryWrapper<TzFuelReport>()
//                            .eq(TzFuelReport::getShipName,dto.getShipName())
//                            .gt(TzFuelReport::getVlsfoValue,0)
//                            .le(TzFuelReport::getFuelTime,dto.getDeliveryTime())
//                            .orderByDesc(TzFuelReport::getFuelTime)
//                            .last("limit 3")
//            );
//
//            BigDecimal dataCount = dto.getVlsfo();
//
//            BigDecimal vlsValue = BigDecimal.ZERO;
//            for (TzFuelReport fuelReport : fuelReports) {
//                if(fuelReport.getVlsfoValue() != null){
//                    vlsValue = vlsValue.add(fuelReport.getVlsfoValue());
//                }
//            }
//            if(dataCount.compareTo(vlsValue) < 0){
//                if(fuelReports.size() == 1){
//                    TzFuelReport fuelReport = fuelReports.get(0);
//                    dto.setVlsfoOne(dataCount);
//                    dto.setVlsfoOnePrice(fuelReport.getVlsfoPrice());
//                    if(dataCount != null && dto.getVlsfoOnePrice() != null){
//                        BigDecimal settlement = dto.getVlsfoOne().multiply(dto.getVlsfoOnePrice());
//                        dto.setVlsfoSettlement(settlement);
//                    }
//                }else if(fuelReports.size() == 2){
//                    TzFuelReport fuelReport = fuelReports.get(0);
//                    if(dataCount.compareTo(fuelReport.getVlsfoValue()) < 1){
//                        dto.setVlsfoOne(dataCount);
//                        dto.setVlsfoOnePrice(fuelReport.getVlsfoPrice());
//                        if(dto.getVlsfoOne() != null && dto.getVlsfoOnePrice() != null){
//                            BigDecimal settlement = dto.getVlsfoOne().multiply(dto.getVlsfoOnePrice());
//                            dto.setVlsfoSettlement(settlement);
//                        }
//                    }else{
//                        BigDecimal lessValue = dataCount.subtract(fuelReport.getVlsfoValue());
//                        TzFuelReport fuelReport1 = fuelReports.get(1);
//                        dto.setVlsfoOne(lessValue);
//                        dto.setVlsfoOnePrice(fuelReport1.getVlsfoPrice());
//                        dto.setVlsfoTwo(fuelReport.getVlsfoValue());
//                        dto.setVlsfoTwoPrice(fuelReport.getVlsfoPrice());
//                        BigDecimal settlement = BigDecimal.ZERO;
//                        if(dto.getVlsfoOne() != null && dto.getVlsfoOnePrice() != null){
//                            settlement = settlement.add(dto.getVlsfoOne().multiply(dto.getVlsfoOnePrice()));
//                        }
//                        if(dto.getVlsfoTwo() != null && dto.getVlsfoTwoPrice() != null){
//                            settlement = settlement.add(dto.getVlsfoTwo().multiply(dto.getVlsfoTwoPrice()));
//                        }
//                        dto.setVlsfoSettlement(settlement);
//                    }
//                }else{
//                    TzFuelReport fuelReport = fuelReports.get(0);
//                    if(dataCount.compareTo(fuelReport.getVlsfoValue()) < 1){
//                        dto.setVlsfoOne(dataCount);
//                        dto.setVlsfoOnePrice(fuelReport.getVlsfoPrice());
//                        if(dto.getVlsfoOne() != null && dto.getVlsfoOnePrice() != null){
//                            BigDecimal settlement = dto.getVlsfoOne().multiply(dto.getVlsfoOnePrice());
//                            dto.setVlsfoSettlement(settlement);
//                        }
//                    }else{
//                        BigDecimal lessValue = dataCount.subtract(fuelReport.getVlsfoValue());
//                        TzFuelReport fuelReport1 = fuelReports.get(1);
//                        if(lessValue.compareTo(fuelReport1.getVlsfoValue()) < 1){
//                            dto.setVlsfoOne(lessValue);
//                            dto.setVlsfoOnePrice(fuelReport1.getVlsfoPrice());
//                            dto.setVlsfoTwo(fuelReport.getVlsfoValue());
//                            dto.setVlsfoTwoPrice(fuelReport.getVlsfoPrice());
//                            BigDecimal settlement = BigDecimal.ZERO;
//                            if(dto.getVlsfoOne() != null && dto.getVlsfoOnePrice() != null){
//                                settlement = settlement.add(dto.getVlsfoOne().multiply(dto.getVlsfoOnePrice()));
//                            }
//                            if(dto.getVlsfoTwo() != null && dto.getVlsfoTwoPrice() != null){
//                                settlement = settlement.add(dto.getVlsfoTwo().multiply(dto.getVlsfoTwoPrice()));
//                            }
//                            dto.setVlsfoSettlement(settlement);
//                        }else{
//                            BigDecimal lessValue2 = lessValue.subtract(fuelReport1.getVlsfoValue());
//                            TzFuelReport fuelReport2 = fuelReports.get(2);
//                            dto.setVlsfoOne(lessValue2);
//                            dto.setVlsfoOnePrice(fuelReport2.getVlsfoPrice());
//                            dto.setVlsfoTwo(fuelReport1.getVlsfoValue());
//                            dto.setVlsfoTwoPrice(fuelReport1.getVlsfoPrice());
//                            dto.setVlsfoThree(fuelReport.getVlsfoValue());
//                            dto.setVlsfoThreePrice(fuelReport.getVlsfoPrice());
//                            BigDecimal settlement = BigDecimal.ZERO;
//                            if(dto.getVlsfoOne() != null && dto.getVlsfoOnePrice() != null){
//                                settlement = settlement.add(dto.getVlsfoOne().multiply(dto.getVlsfoOnePrice()));
//                            }
//                            if(dto.getVlsfoTwo() != null && dto.getVlsfoTwoPrice() != null){
//                                settlement = settlement.add(dto.getVlsfoTwo().multiply(dto.getVlsfoTwoPrice()));
//                            }
//                            if(dto.getVlsfoThree() != null && dto.getVlsfoThreePrice() != null){
//                                settlement = settlement.add(dto.getVlsfoThree().multiply(dto.getVlsfoThreePrice()));
//                            }
//                            dto.setVlsfoSettlement(settlement);
//                        }
//                    }
//                }
//            }
//        }
//        if(dto.getLsmgo() != null) {
//            //获取交还船时间之前的三条记录
//            List<TzFuelReport> fuelReports = tzFuelReportService.getBaseMapper().selectList(
//                    new LambdaQueryWrapper<TzFuelReport>()
//                            .eq(TzFuelReport::getShipName, dto.getShipName())
//                            .gt(TzFuelReport::getLsmgoValue, 0)
//                            .le(TzFuelReport::getFuelTime, dto.getDeliveryTime())
//                            .orderByDesc(TzFuelReport::getFuelTime)
//                            .last("limit 3")
//            );
//            BigDecimal dataCount = dto.getLsmgo();
//
//            BigDecimal lsmValue = BigDecimal.ZERO;
//            for (TzFuelReport fuelReport : fuelReports) {
//                if (fuelReport.getLsmgoValue() != null) {
//                    lsmValue = lsmValue.add(fuelReport.getLsmgoValue());
//                }
//            }
//            if (dataCount.compareTo(lsmValue) < 0) {
//                if (fuelReports.size() == 1) {
//                    TzFuelReport fuelReport = fuelReports.get(0);
//                    if (dataCount.compareTo(fuelReport.getLsmgoValue()) < 1) {
//                        dto.setLsmgoOne(dataCount);
//                        dto.setLsmgoOnePrice(fuelReport.getLsmgoPrice());
//                        if (dto.getLsmgoOne() != null && dto.getLsmgoOnePrice() != null) {
//                            BigDecimal settlement = dto.getLsmgoOne().multiply(dto.getLsmgoOnePrice());
//                            dto.setLsmgoSettlement(settlement);
//                        }
//                    }
//                } else if (fuelReports.size() == 2) {
//                    TzFuelReport fuelReport = fuelReports.get(0);
//                    if (dataCount.compareTo(fuelReport.getLsmgoValue()) < 1) {
//                        dto.setLsmgoOne(dataCount);
//                        dto.setLsmgoOnePrice(fuelReport.getLsmgoPrice());
//                        if (dto.getLsmgoOne() != null && dto.getLsmgoOnePrice() != null) {
//                            BigDecimal settlement = dto.getLsmgoOne().multiply(dto.getLsmgoOnePrice());
//                            dto.setLsmgoSettlement(settlement);
//                        }
//                    } else {
//                        BigDecimal lessValue = dataCount.subtract(fuelReport.getLsmgoValue());
//                        TzFuelReport fuelReport1 = fuelReports.get(1);
//                        dto.setLsmgoOne(lessValue);
//                        dto.setLsmgoOnePrice(fuelReport1.getLsmgoPrice());
//                        dto.setLsmgoTwo(fuelReport.getLsmgoValue());
//                        dto.setLsmgoTwoPrice(fuelReport.getLsmgoPrice());
//                        BigDecimal settlement = BigDecimal.ZERO;
//                        if (dto.getLsmgoOne() != null && dto.getLsmgoOnePrice() != null) {
//                            settlement = settlement.add(dto.getLsmgoOne().multiply(dto.getLsmgoOnePrice()));
//                        }
//                        if (dto.getLsmgoTwo() != null && dto.getLsmgoTwoPrice() != null) {
//                            settlement = settlement.add(dto.getLsmgoTwo().multiply(dto.getLsmgoTwoPrice()));
//                        }
//                        dto.setLsmgoSettlement(settlement);
//                    }
//                } else {
//                    TzFuelReport fuelReport = fuelReports.get(0);
//                    if (dataCount.compareTo(fuelReport.getLsmgoValue()) < 1) {
//                        dto.setLsmgoOne(dataCount);
//                        dto.setLsmgoOnePrice(fuelReport.getLsmgoPrice());
//                        if (dto.getLsmgoOne() != null && dto.getLsmgoOnePrice() != null) {
//                            BigDecimal settlement = dto.getLsmgoOne().multiply(dto.getLsmgoOnePrice());
//                            dto.setLsmgoSettlement(settlement);
//                        }
//                    } else {
//                        BigDecimal lessValue = dataCount.subtract(fuelReport.getLsmgoValue());
//                        TzFuelReport fuelReport1 = fuelReports.get(1);
//                        if (lessValue.compareTo(fuelReport1.getLsmgoValue()) < 1) {
//                            dto.setLsmgoOne(lessValue);
//                            dto.setLsmgoOnePrice(fuelReport1.getLsmgoPrice());
//                            dto.setLsmgoTwo(fuelReport.getLsmgoValue());
//                            dto.setLsmgoTwoPrice(fuelReport.getLsmgoPrice());
//                            BigDecimal settlement = BigDecimal.ZERO;
//                            if (dto.getLsmgoOne() != null && dto.getLsmgoOnePrice() != null) {
//                                settlement = settlement.add(dto.getLsmgoOne().multiply(dto.getLsmgoOnePrice()));
//                            }
//                            if (dto.getLsmgoTwo() != null && dto.getLsmgoTwoPrice() != null) {
//                                settlement = settlement.add(dto.getLsmgoTwo().multiply(dto.getLsmgoTwoPrice()));
//                            }
//                            dto.setLsmgoSettlement(settlement);
//                        } else {
//                            BigDecimal lessValue2 = lessValue.subtract(fuelReport1.getLsmgoValue());
//                            TzFuelReport fuelReport2 = fuelReports.get(2);
//                            dto.setLsmgoOne(lessValue2);
//                            dto.setLsmgoOnePrice(fuelReport2.getLsmgoPrice());
//                            dto.setLsmgoTwo(fuelReport1.getLsmgoValue());
//                            dto.setLsmgoTwoPrice(fuelReport1.getLsmgoPrice());
//                            dto.setLsmgoThree(fuelReport.getLsmgoValue());
//                            dto.setLsmgoThreePrice(fuelReport.getLsmgoPrice());
//                            BigDecimal settlement = BigDecimal.ZERO;
//                            if (dto.getLsmgoOne() != null && dto.getLsmgoOnePrice() != null) {
//                                settlement = settlement.add(dto.getLsmgoOne().multiply(dto.getLsmgoOnePrice()));
//                            }
//                            if (dto.getLsmgoTwo() != null && dto.getLsmgoTwoPrice() != null) {
//                                settlement = settlement.add(dto.getLsmgoTwo().multiply(dto.getLsmgoTwoPrice()));
//                            }
//                            if (dto.getLsmgoThree() != null && dto.getLsmgoThreePrice() != null) {
//                                settlement = settlement.add(dto.getLsmgoThree().multiply(dto.getLsmgoThreePrice()));
//                            }
//                            dto.setLsmgoSettlement(settlement);
//                        }
//                    }
//                }
//            }
//        }
        return dto;
    }

    @Override
    public Long dataTransfer(TzFuelDelivery dto) {
        String contractType = dto.getContractType();
        int deliveryType = dto.getDeliveryType();

        String fuelType = "";
        if(StringUtils.equals("1",contractType)){
            contractType = "租入长期船";
            fuelType = "交船结算";
        }else if(StringUtils.equals("2",contractType)){
            contractType = "租入短期船";
            fuelType = "交船结算";
        }else if(StringUtils.equals("3",contractType)){
            contractType = "船舶租出";
//            fuelType = "还船结算";
        }else{
            contractType = "内部转租";
        }
        dto.setContractType(contractType);

        if(StringUtils.isNotBlank(dto.getFileInfo())){
            String[] fileId = dto.getFileInfo().split(",");
            List<SpFobFileRecord> fileRecords = spFobFileRecordService.listByIds(Arrays.asList(fileId));
            if(fileRecords.size() > 0){
                JSONArray fileArray = new JSONArray();
                for (SpFobFileRecord fileRecord : fileRecords) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("fileName",fileRecord.getName());
                    jsonObject.put("filePath",fileRecord.getPath());
                    fileArray.add(jsonObject);
                }
                dto.setFileInfo(fileArray.toJSONString());
                dto.setFilePathInfo(fileRecords.stream().map(SpFobFileRecord::getPath).collect(Collectors.joining(",")));
            }
        }

        if(deliveryType == 1){
            dto.setEventType("交船（"+dto.getShipOwner()+"交船给"+dto.getLessee()+"）");
        }else{
            dto.setEventType("还船（"+dto.getLessee()+"还船给"+dto.getShipOwner()+"）");
        }

        dto = resetDeliveryData(dto);
        this.saveOrUpdate(dto);

        if(StringUtils.isNotBlank(fuelType)){
            //每种量价都需要同步一条加油数据
            if(dto.getVlsfoOne() != null || dto.getVlsfoOnePrice() != null
                    || dto.getLsmgoOne() != null || dto.getLsmgoOnePrice() != null){
                //量1价1
                TzFuelReport saveData = new TzFuelReport();

                if(StringUtils.isNotBlank(dto.getProcessInstanceId())){
                    //传入流程实例ID的情况下，需要校验同一流程下是否已同步过交还船数据，如果同步过了则更新
                    saveData = tzFuelReportService.getBaseMapper().selectOne(
                            new LambdaQueryWrapper<TzFuelReport>()
                                    .eq(TzFuelReport::getProcessInstanceId,dto.getProcessInstanceId())
                                    .eq(TzFuelReport::getFuelType,fuelType)
                                    .eq(TzFuelReport::getValueType,1)
                                    .last("limit 1")
                    );
                    if(saveData == null){
                        saveData = new TzFuelReport();
                    }
                }
                saveData.setFuelType(fuelType);
                saveData.setShipName(dto.getShipName());
                saveData.setImo(dto.getImo());
                saveData.setFuelTime(dto.getDeliveryTime());
                saveData.setDataType(2);
                saveData.setLsmgoValue(dto.getLsmgoOne());
                saveData.setLsmgoPrice(dto.getLsmgoOnePrice());
                saveData.setVlsfoPrice(dto.getVlsfoOnePrice());
                saveData.setVlsfoValue(dto.getVlsfoOne());
                saveData.setUpdatedBy(SecurityUtils.getUsername());
                saveData.setUpdatedTime(new Date());
                saveData.setValueType(1);
                saveData.setProcessInstanceId(dto.getProcessInstanceId());
                tzFuelReportService.saveOrUpdate(saveData);
            }
            if(dto.getVlsfoTwo() != null || dto.getVlsfoTwoPrice() != null
                    || dto.getLsmgoTwo() != null || dto.getLsmgoTwoPrice() != null){
                //量2价2
                TzFuelReport saveData = new TzFuelReport();

                if(StringUtils.isNotBlank(dto.getProcessInstanceId())){
                    //传入流程实例ID的情况下，需要校验同一流程下是否已同步过交还船数据，如果同步过了则更新
                    saveData = tzFuelReportService.getBaseMapper().selectOne(
                            new LambdaQueryWrapper<TzFuelReport>()
                                    .eq(TzFuelReport::getProcessInstanceId,dto.getProcessInstanceId())
                                    .eq(TzFuelReport::getFuelType,fuelType)
                                    .eq(TzFuelReport::getValueType,2)
                                    .last("limit 1")
                    );
                    if(saveData == null){
                        saveData = new TzFuelReport();
                    }
                }
                saveData.setFuelType(fuelType);
                saveData.setShipName(dto.getShipName());
                saveData.setImo(dto.getImo());
                saveData.setFuelTime(dto.getDeliveryTime());
                saveData.setDataType(2);
                saveData.setLsmgoValue(dto.getLsmgoTwo());
                saveData.setLsmgoPrice(dto.getLsmgoTwoPrice());
                saveData.setVlsfoPrice(dto.getVlsfoTwoPrice());
                saveData.setVlsfoValue(dto.getVlsfoTwo());
                saveData.setUpdatedBy(SecurityUtils.getUsername());
                saveData.setUpdatedTime(new Date());
                saveData.setValueType(2);
                saveData.setProcessInstanceId(dto.getProcessInstanceId());
                tzFuelReportService.saveOrUpdate(saveData);
            }
            if(dto.getVlsfoThree() != null || dto.getVlsfoThreePrice() != null
                    || dto.getLsmgoThree() != null || dto.getLsmgoThreePrice() != null){
                //量3价3
                TzFuelReport saveData = new TzFuelReport();

                if(StringUtils.isNotBlank(dto.getProcessInstanceId())){
                    //传入流程实例ID的情况下，需要校验同一流程下是否已同步过交还船数据，如果同步过了则更新
                    saveData = tzFuelReportService.getBaseMapper().selectOne(
                            new LambdaQueryWrapper<TzFuelReport>()
                                    .eq(TzFuelReport::getProcessInstanceId,dto.getProcessInstanceId())
                                    .eq(TzFuelReport::getFuelType,fuelType)
                                    .eq(TzFuelReport::getValueType,3)
                                    .last("limit 1")
                    );
                    if(saveData == null){
                        saveData = new TzFuelReport();
                    }
                }
                saveData.setFuelType(fuelType);
                saveData.setShipName(dto.getShipName());
                saveData.setImo(dto.getImo());
                saveData.setFuelTime(dto.getDeliveryTime());
                saveData.setDataType(2);
                saveData.setLsmgoValue(dto.getLsmgoThree());
                saveData.setLsmgoPrice(dto.getLsmgoThreePrice());
                saveData.setVlsfoPrice(dto.getVlsfoThreePrice());
                saveData.setVlsfoValue(dto.getVlsfoThree());
                saveData.setUpdatedBy(SecurityUtils.getUsername());
                saveData.setUpdatedTime(new Date());
                saveData.setValueType(3);
                saveData.setProcessInstanceId(dto.getProcessInstanceId());
                tzFuelReportService.saveOrUpdate(saveData);
            }
        }

        return dto.getId();
    }

    @Override
    public JsonResult<Page<TzFuelDelivery>> getPage(TzFuelDelivery dto) {
        dto.setOrderField("delivery_time");
        QueryWrapper wrapper = new QueryWrapper();
//        if(dto.getSelectType() != null && dto.getSelectType().intValue() == 1){
//            wrapper.gt("vlsfo",0);
//        }else{
//            wrapper.gt("lsmgo",0);
//        }
        Page<TzFuelDelivery> resultPage = this.page(dto,wrapper);
        return JsonResult.success(resultPage);
    }

    @Override
    public JsonResult dataExport(TzFuelDelivery dto) throws IOException {
        dto.setOrderField("delivery_time");
        QueryWrapper wrapper = new QueryWrapper();
        String type = "LSMGO";
        if(dto.getSelectType() != null && dto.getSelectType().intValue() == 1){
//            wrapper.gt("vlsfo",0);
            type = "VLSFO";
        }else{
//            wrapper.gt("lsmgo",0);
        }
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if(dto.getIds() != null && dto.getIds().size() > 0){
            queryWrapper.in("id",dto.getIds());
        }
        List<TzFuelDelivery> dataList = this.pageExportList(dto,queryWrapper,new LinkedList<>());
        String shipName = "";
        if(dataList.size() > 0){
            shipName = dataList.get(0).getShipName()+"-";
        }
        String fileName = shipName+"交还船记录"+type+"-"+ DateFormatUtils.format(new Date(), "yyyy-MM-dd");
        //创建临时文件
        File tempFileExcel = new File(fileName+".xlsx");

        if(dto.getSelectType() != null && dto.getSelectType().intValue() == 1){
            List<TzFuelDeliveryVlsfoBo> boList = new LinkedList<>();
            for (TzFuelDelivery fuelDelivery : dataList) {
                TzFuelDeliveryVlsfoBo vlsfoBo = new TzFuelDeliveryVlsfoBo();
                vlsfoBo.setShipName(fuelDelivery.getShipName());
                vlsfoBo.setEventType(fuelDelivery.getEventType());
                vlsfoBo.setContractType(fuelDelivery.getContractType());
                vlsfoBo.setDeliveryTime(fuelDelivery.getDeliveryTime());
                vlsfoBo.setVlsfoStr(fuelDelivery.getVlsfoStr());
                vlsfoBo.setVlsfoOneStr(fuelDelivery.getVlsfoOneStr());
                vlsfoBo.setVlsfoOnePriceStr(fuelDelivery.getVlsfoOnePriceStr());
                vlsfoBo.setVlsfoTwoStr(fuelDelivery.getVlsfoTwoStr());
                vlsfoBo.setVlsfoTwoPriceStr(fuelDelivery.getVlsfoTwoPriceStr());
                vlsfoBo.setVlsfoThreeStr(fuelDelivery.getVlsfoThreeStr());
                vlsfoBo.setVlsfoThreePriceStr(fuelDelivery.getVlsfoThreePriceStr());
                vlsfoBo.setVlsfoSettlementStr(fuelDelivery.getVlsfoSettlementStr());
                boList.add(vlsfoBo);
            }
            EasyExcel.write(fileName+".xlsx", TzFuelDeliveryVlsfoBo.class).sheet("交还船记录").doWrite(boList);
        }else{
            List<TzFuelDeliveryLsmgoBo> boList = new LinkedList<>();
            for (TzFuelDelivery fuelDelivery : dataList) {
                TzFuelDeliveryLsmgoBo lsmgoBo = new TzFuelDeliveryLsmgoBo();
                lsmgoBo.setShipName(fuelDelivery.getShipName());
                lsmgoBo.setEventType(fuelDelivery.getEventType());
                lsmgoBo.setContractType(fuelDelivery.getContractType());
                lsmgoBo.setDeliveryTime(fuelDelivery.getDeliveryTime());
                lsmgoBo.setLsmgoStr(fuelDelivery.getLsmgoStr());
                lsmgoBo.setLsmgoOneStr(fuelDelivery.getLsmgoOneStr());
                lsmgoBo.setLsmgoOnePriceStr(fuelDelivery.getLsmgoOnePriceStr());
                lsmgoBo.setLsmgoTwoStr(fuelDelivery.getLsmgoTwoStr());
                lsmgoBo.setLsmgoTwoPriceStr(fuelDelivery.getLsmgoTwoPriceStr());
                lsmgoBo.setLsmgoThreeStr(fuelDelivery.getLsmgoThreeStr());
                lsmgoBo.setLsmgoThreePriceStr(fuelDelivery.getLsmgoThreePriceStr());
                lsmgoBo.setLsmgoSettlementStr(fuelDelivery.getLsmgoSettlementStr());
                boList.add(lsmgoBo);
            }
            EasyExcel.write(fileName+".xlsx", TzFuelDeliveryLsmgoBo.class).sheet("交还船记录").doWrite(boList);
        }

        List<File> downloadFiles = new LinkedList<>();
        downloadFiles.add(tempFileExcel);

        //创建临时压缩文件
        File zipFile = new File(fileName+".zip");
        for (TzFuelDelivery fuelDelivery : dataList) {
            if(StringUtils.isBlank(fuelDelivery.getFilePathInfo())){
                continue;
            }
            String[] filePathArr = fuelDelivery.getFilePathInfo().split(",");
            for (String s : filePathArr) {
                //文件下载进压缩包
                String CsoldPart = "http://10.75.34.224:9300/statics";
                String ZsoldPart = "http://10.75.33.149:9300/statics";
                String CsPart = "https://lngshippingcs.cgp.cnooc/api/file/statics";
                String ZsPart = "https://lngshipping.cgp.cnooc/api/file/statics";

                String newUrl = "";
                if (s.contains("https://lngshipping.cgp.cnooc")) {
                    newUrl = s.replace(ZsPart, ZsoldPart);
                }else if (s.contains("https://lngshippingcs.cgp.cnooc")){
                    newUrl = s.replace(CsPart, CsoldPart);
                }else {
                    newUrl = s;
                }
                //文件下载进压缩包
                URL otherUrl = new URL(newUrl);
                InputStream otherInputStream = otherUrl.openStream();
                int spIndex = s.lastIndexOf(".");
                File tempFile = File.createTempFile(fuelDelivery.getShipName()+"-"+fuelDelivery.getDeliveryTime()+"-附件信息", s.substring(spIndex));
                try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = otherInputStream.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, bytesRead);
                    }
                }
                downloadFiles.add(tempFile);
            }
        }
        try (FileOutputStream fos = new FileOutputStream(zipFile);
             ZipOutputStream zos = new ZipOutputStream(fos)) {
            for (File downloadFile : downloadFiles) {
                ZipEntry zipEntry = new ZipEntry(downloadFile.getName());
                zos.putNextEntry(zipEntry);
                try (FileInputStream fis = new FileInputStream(downloadFile)) {
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = fis.read(buffer)) > 0) {
                        zos.write(buffer, 0, length);
                    }
                }
                zos.closeEntry();
                downloadFile.delete();
            }
        }
        FileInputStream input = new FileInputStream(zipFile);
        MultipartFile multipartFile = new MockMultipartFile("file", zipFile.getName(), "application/octet-stream", input);
        R<SysFile> result1 = remoteFileService.upload(multipartFile);
        if(result1.getCode() != R.SUCCESS){
            zipFile.delete();
            tempFileExcel.delete();
            throw new BusException("文件服务器连接失败", BaseResultCode.GENERAL_ERROR);
        }
        String urls = result1.getData().getHttpsUrl();
        zipFile.delete();
        tempFileExcel.delete();
        return JsonResult.success(urls);
    }
}




